<?php

namespace app\common\model;

use think\Model;

/**
 * 优惠券
 */
class Coupon extends Model
{

    // 表名
    protected $name = 'coupon';

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;

    const USE_NO = 1;
    const USE_YES = 2;

    public function couponSetting()
    {
        return $this->belongsTo('coupon_setting', 'setting_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    /**
     * 根据用户id获取未使用的优惠券数量
     * @param $member_id
     * @return int|string
     * @throws \think\Exception
     */
    public static function getCouponNumByMemberId($member_id)
    {
        return self::where(['member_id'=>$member_id,'status'=>1,'end_time'=>['gt',time()]])->count();
    }

    /**
     * 根据用户id获取未使用的优惠券
     * @param $member_id
     * @param int $coupon_status
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public static function getCouponListByMemberId($member_id,$coupon_status=1)
    {
        if ($coupon_status == 1) {
            $where['a.status'] = 1;
            $where['a.end_time'] = ['EGT', time()];
        }elseif ($coupon_status == 2){
            $where['a.status'] = 2;
        }else{
            $where['a.coupon_status'] = 1;
            $where['a.end_time'] = ['LT', time()];
        }
        $where['a.member_id'] = $member_id;
        $list = self::alias('a')->field('b.name,a.id,a.money,a.least_cost,a.begin_time,a.end_time')
            ->join('coupon_setting b','a.setting_id=b.id','left')
            ->where($where)
            ->order('a.id desc')->paginate(10)->each(function ($item, $key) use ($coupon_status) {
                $item['least_cost'] = htmlspecialchars_decode($item['least_cost']);
                $item['coupon_status'] = $coupon_status;
                $item['name'] = htmlspecialchars_decode($item['name']);
                $item['begin_time'] = date('Y.m.d', $item['begin_time']);
                $item['end_time'] = date('Y.m.d', $item['end_time']);
                return $item;
            });
        $list = $list->toArray();
        return $list;
    }

    /**
     * 判断优惠劵是否可用
     * @param $couponId
     * @param $memberId
     * @param $leastCost
     * @return array|bool|\PDOStatement|string|Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function checkCoupon($couponId, $memberId, $leastCost)
    {
        return self::where([
            'id' => $couponId,
            'member_id' => $memberId,
            'status' => self::USE_NO
        ])
            ->where('least_cost', '<=', $leastCost)
            ->where('end_time', '>', time())
            ->find();
    }
}
